<template>
  <div class="flex h-full flex-1 gap-3">
    <!-- 左侧用户列表 -->
    <div class="w-1/4 bg-white rounded-lg p-3">
      <div class="flex items-center mb-3 gap-3">
        <div class="text-lg">用户列表</div>
        <el-tag size="small" type="success">在线</el-tag>
      </div>
      
      <!-- 搜索框 -->
      <div class="mb-3 flex items-center gap-3">
        
        <el-input v-model="searchKeyword" placeholder="搜索用户" prefix-icon="Search" clearable />
        <div class="flex-1">
            <el-button type="primary" class="p-2">搜索</el-button>
        </div>        
      </div>

      <!-- 用户列表 -->
      <div class="overflow-y-auto" style="height: calc(100vh - 180px)">
        <div
          v-for="user in filteredUsers"
          :key="user.id"
          class="flex items-center p-3 mb-2 rounded-lg cursor-pointer hover:bg-gray-100"
          :class="{ 'bg-blue-50': currentUser?.id === user.id }"
          @click="selectUser(user)"
        >
          <el-avatar :size="40" :src="user.avatar" />
          <div class="ml-3 flex-1">
            <div class="flex items-center justify-between">
              <span class="font-medium">{{ user.name }}</span>
              <el-tag size="small" :type="user.type === 'vip' ? 'danger' : ''">
                {{ user.type === 'vip' ? 'VIP' : '普通' }}
              </el-tag>
            </div>
            <div class="text-sm text-gray-500 mt-1">{{ user.lastMessage }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="flex-1 bg-white rounded-lg flex flex-col">
      <template v-if="currentUser">
        <!-- 聊天头部 -->
        <div class="p-4 border-b">
          <div class="flex items-center justify-between">
            <div>
              <span class="text-lg font-medium">{{ currentUser.name }}</span>
              <el-tag size="small" class="ml-2">{{ currentUser.type === 'vip' ? 'VIP用户' : '普通用户' }}</el-tag>
            </div>
            <div>
              <!-- <el-button type="primary" size="small" @click="showUserInfo">查看资料</el-button>
              <el-button type="success" size="small" @click="startVideoCall">视频通话</el-button> -->
            </div>
          </div>
        </div>

        <!-- 聊天记录区域 -->
        <div class="flex-1 overflow-y-auto p-4" ref="chatContainer">
          <div v-for="msg in chatMessages" :key="msg.id" class="mb-4">
            <div :class="['flex', msg.isSelf ? 'justify-end' : 'justify-start']">
              <div :class="['max-w-[70%]', msg.isSelf ? 'items-end' : 'items-start']">
                <div class="flex items-center mb-1">
                  <span class="text-sm text-gray-500">{{ msg.time }}</span>
                  <span class="mx-2 text-sm">{{ msg.sender }}</span>
                </div>
                
                <!-- 文本消息 -->
                <div v-if="msg.type === 'text'"
                  :class="[
                    'p-3 rounded-lg',
                    msg.isSelf ? 'bg-blue-500 text-white' : 'bg-gray-100'
                  ]"
                >
                  {{ msg.content }}
                </div>

                <!-- 图片消息 -->
                <div v-else-if="msg.type === 'image'"
                  class="max-w-sm cursor-pointer"
                  @click="previewImage(msg.content)"
                >
                  <el-image 
                    :src="msg.content" 
                    :preview-src-list="[msg.content]"
                    fit="cover"
                    class="rounded-lg"
                  />
                </div>

                <!-- 文件消息 -->
                <div v-else-if="msg.type === 'file'"
                  :class="[
                    'p-3 rounded-lg flex items-center',
                    msg.isSelf ? 'bg-blue-500 text-white' : 'bg-gray-100'
                  ]"
                >
                  <el-icon class="mr-2"><Document /></el-icon>
                  <div class="flex-1">
                    <div class="text-sm">{{ msg.fileName }}</div>
                    <div class="text-xs opacity-75">{{ msg.fileSize }}</div>
                  </div>
                  <el-button link @click="downloadFile(msg)">下载</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="border-t p-4">
          <div class="flex items-center mb-2">
            <el-upload
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleImageUpload"
            >
              <el-button :icon="Picture">图片</el-button>
            </el-upload>
            <el-upload
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileUpload"
            >
              <el-button :icon="Folder">文件</el-button>
            </el-upload>
            <el-button :icon="VideoCamera" @click="startVideoCall">视频</el-button>
            <el-button :icon="QuestionFilled" @click="showQuickReplies">快捷回复</el-button>
          </div>
          <div class="flex gap-2">
            <el-input
              v-model="messageInput"
              type="textarea"
              :rows="3"
              placeholder="请输入消息..."
              @keyup.enter.ctrl="sendMessage"
            />
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </div>
        </div>
      </template>

      <!-- 未选择用户时的提示 -->
      <template v-else>
        <div class="h-full flex items-center justify-center text-gray-400">
          请选择一个用户开始聊天
        </div>
      </template>
    </div>
  </div>

  <!-- 快捷回复抽屉 -->
  <el-drawer
    v-model="quickReplyDrawer"
    title="快捷回复"
    direction="rtl"
    size="300px"
  >
    <div class="p-4">
      <el-input
        v-model="quickReplySearch"
        placeholder="搜索快捷回复"
        prefix-icon="Search"
        clearable
        class="mb-4"
      />
      <div class="space-y-2">
        <div
          v-for="reply in filteredQuickReplies"
          :key="reply.id"
          class="p-3 bg-gray-50 rounded cursor-pointer hover:bg-gray-100"
          @click="useQuickReply(reply)"
        >
          {{ reply.content }}
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { 
  Picture, 
  Folder, 
  VideoCamera, 
  QuestionFilled, 
  Document, 
  Search 
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 用户列表数据
const users = ref([
  {
    id: 1,
    name: '张三',
    type: 'vip',
    avatar: 'https://placeholder.com/50',
    lastMessage: '好的，我明白了'
  },
  {
    id: 2,
    name: '李四',
    type: 'normal',
    avatar: 'https://placeholder.com/50',
    lastMessage: '请问医生...'
  }
])

// 搜索功能
const searchKeyword = ref('')
const filteredUsers = computed(() => {
  return users.value.filter(user => 
    user.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 当前选中的用户
const currentUser = ref(null)
const selectUser = (user) => {
  currentUser.value = user
  loadChatHistory(user.id)
}

// 聊天消息
const chatMessages = ref([])
const messageInput = ref('')
const chatContainer = ref(null)

// 加载聊天历史
const loadChatHistory = (userId) => {
  // 模拟加载历史消息
  chatMessages.value = [
    {
      id: 1,
      type: 'text',
      content: '您好，请问有什么可以帮您？',
      sender: '客服',
      time: '10:00',
      isSelf: true
    },
    {
      id: 2,
      type: 'text',
      content: '我想咨询一下感冒症状',
      sender: '张三',
      time: '10:01',
      isSelf: false
    }
  ]
  scrollToBottom()
}

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim()) return
  
  const newMessage = {
    id: Date.now(),
    type: 'text',
    content: messageInput.value,
    sender: '客服',
    time: new Date().toLocaleTimeString(),
    isSelf: true
  }
  
  chatMessages.value.push(newMessage)
  messageInput.value = ''
  await scrollToBottom()
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 文件上传处理
const handleImageUpload = (file) => {
  // 处理图片上传
  const reader = new FileReader()
  reader.onload = (e) => {
    chatMessages.value.push({
      id: Date.now(),
      type: 'image',
      content: e.target.result,
      sender: '客服',
      time: new Date().toLocaleTimeString(),
      isSelf: true
    })
    scrollToBottom()
  }
  reader.readAsDataURL(file.raw)
}

const handleFileUpload = (file) => {
  chatMessages.value.push({
    id: Date.now(),
    type: 'file',
    content: URL.createObjectURL(file.raw),
    fileName: file.name,
    fileSize: `${(file.size / 1024).toFixed(2)}KB`,
    sender: '客服',
    time: new Date().toLocaleTimeString(),
    isSelf: true
  })
  scrollToBottom()
}

// 快捷回复功能
const quickReplyDrawer = ref(false)
const quickReplySearch = ref('')
const quickReplies = ref([
  { id: 1, content: '您好，请问有什么可以帮您？' },
  { id: 2, content: '好的，我明白了，请稍等' },
  { id: 3, content: '建议您到医院就医做进一步检查' }
])

const filteredQuickReplies = computed(() => {
  return quickReplies.value.filter(reply =>
    reply.content.toLowerCase().includes(quickReplySearch.value.toLowerCase())
  )
})

const showQuickReplies = () => {
  quickReplyDrawer.value = true
}

const useQuickReply = (reply) => {
  messageInput.value = reply.content
  quickReplyDrawer.value = false
}

// 其他功能
const showUserInfo = () => {
  ElMessage.success('查看用户资料')
}

const startVideoCall = () => {
  ElMessage.success('发起视频通话')
}

const downloadFile = (file) => {
  ElMessage.success('开始下载文件')
}

const previewImage = (url) => {
  // 图片预览逻辑
}
</script>

<style scoped>
:deep(.el-upload) {
  margin-right: 8px;
}
</style>